package com.tm.controller;

import com.tm.service.UserTanhuaService;
import com.tm.service.userService;
import com.tm.util.SendSmsutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import tm.pojo.UserPojo;
import tm.pojo.dto.HomePageDto;
import tm.result.Result;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Rocky
 * @create 2022-09-25 13:41
 */
@RestController
@RequestMapping("login")
public class loginController {

    @Autowired
    private RedisTemplate  redisTemplate;

    @Autowired
    private userService userService;


    //发送验证码注册的接口
    @PostMapping("sendCode")
    public String sendCode(String phonenumber){
        String s = SendSmsutil.loginsendSms(phonenumber);
//        Object s1 = redisTemplate.opsForValue().get("code_" + phonenumber);
//        System.out.println(s1);
        UserPojo userPojo = queryNumber(phonenumber);
        if (userPojo!=null){
            return "该用户已存在，无法注册";
        }else {
            userService.addUserNumber(phonenumber);
            redisTemplate.opsForValue().set("code_"+phonenumber,s,5,TimeUnit.MINUTES);
        }
        return "登陆成功 填写个人信息 增加魅力";
    }

    public UserPojo queryNumber(String phonenumber){
        return userService.queryNumber(phonenumber);
    }

    //登录更新用户接口
    @PostMapping("addUser")
    public String addUser(@RequestBody UserPojo userPojo, String code){
        String phonenumber = userPojo.getPhonenumber();
        Object o = redisTemplate.opsForValue().get("code_" +userPojo.getPhonenumber());
        if (o==null){
            return "验证码已过期";
        }
        if (code.equals(o.toString())){
            String s = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set("token_"+userPojo.getPhonenumber(),s);
            userService.addUser(userPojo);
            return s;
        }else {
            return "验证码错误";
        }
    }



}
